import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { getCurrentInstance } from 'vue'
import { showNotify } from 'vant'

export const useUser = () => {
  const { proxy } = getCurrentInstance()
  const $router = useRouter()
  // 获取存localStorage的用户名
  const username = ref('')
  username.value = localStorage.getItem('user_username')
  const password = ref('')

  const formRef = ref(null)
  // 验证登录规则
  const rules = ref({
    username: [
      //必选字段 required: true
      { required: true, message: '请填写用户名', trigger: 'onBlur' },
      //pattern	通过正则表达式进行校验，正则无法匹配表示校验不通过
      {
        pattern: /^[0-9a-zA-Z_]{3,12}$/,
        message: '用户名的长度为3~12个字符,名字为大小写字母/数字/下划线',
        trigger: 'onBlur',
      },
    ],
    password: [
      { required: true, message: '请填写密码', trigger: 'onBlur' },
      {
        pattern: /^[0-9]{6,12}$/,
        message: '用户名的长度为6~12个字符,密码只能为数字',
        trigger: 'onBlur',
      },
    ],
  })

  const isShow = ref(false)
  // 控制弹窗是否展示
  const changePW = () => {
    isShow.value = true
  }
  // 修改密码
  const onUpdate = async () => {
    const res = await proxy.$http.put(`/user/update_user_password/${username.value}`, {
      user_password: `${password.value}`,
    })
    if (res.code == 0) {
      isShow.value = false
      // 1.清除登录状态
      localStorage.clear()
      // 2.路由到登录页面
      $router.push('/login')
      showNotify({ type: 'success', message: '修改密码成功,请重新登录', duration: 3000 })
    } else {
      showNotify({ type: 'danger', message: '修改密码失败!!!', duration: 3000 })
    }
  }
  // 注销账号
  const deleteAccount = async () => {
    // 把用户存在的状态更改为"已删除"
    const res = await proxy.$http.put(`/user/user_username/${username.value}`, {
      user_existstatus: '已删除',
    })
    if (res.code == 0) {
      // 1.清除登录状态
      localStorage.clear()
      // 2.路由到登录页面
      $router.push('/login')
      showNotify({ type: 'success', message: '删除用户成功', duration: 1500 })
    }
  }

  // 退出登录
  const onLogout = async () => {
    // 发送请求修改该用户的登录状态
    const id = localStorage.getItem('common_use_id')
    await proxy.$http.put(`/user/${id}`, {
      user_onlinestatus: '未登录',
    })
    // 1.清除登录状态
    localStorage.clear()
    showNotify({ type: 'success', message: '退出成功', duration: 3000 })
    // 2.路由到登录页面
    $router.push('/login')
  }

  return {
    formRef,
    isShow,
    username,
    password,
    rules,
    changePW,
    deleteAccount,
    onLogout,
    onUpdate,
  }
}
